package com.itheima.aop;

import com.itheima.mapper.OperateMapper;
import com.itheima.mapper.UserMapper;
import com.itheima.pojo.OperateLog;
import com.itheima.pojo.User;
import com.itheima.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Arrays;

@Component
@Slf4j
@Aspect
public class LogAspect {
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private OperateMapper operateMapper;
    @Autowired
    private UserMapper userMapper;

    @Around("@annotation(com.itheima.anno.Log)")
    public Object logRecord(ProceedingJoinPoint pjp) throws Throwable {
        OperateLog operateLog = new OperateLog();
        String token = request.getHeader("token");
        Claims claims = JwtUtils.parseJWT(token);
        Integer userId = (Integer) claims.get("id");
        //获取用户姓名
        User user = userMapper.getInfo(userId);
        String username = user.getUsername();
        operateLog.setOperateUser(username);
        //获取用户类型
        Integer type = (Integer) claims.get("type");
        operateLog.setOperateType(type);
        //获取操作参数
        Object[] args = pjp.getArgs();
        String methodParams = Arrays.toString(args);
        operateLog.setOperateParams(methodParams);
        //调用原始方法
        long begin = System.currentTimeMillis();
        Object result = pjp.proceed();
        long end = System.currentTimeMillis();
        //获取操作时间
        operateLog.setCostTime(end - begin);
        operateLog.setOperateTime(LocalDateTime.now());

        operateMapper.insert(operateLog);
        return result;
    }
}
